package com.simple.cloud.core.base;

import cn.hutool.core.util.StrUtil;
import com.mybatisflex.annotation.Column;
import com.mybatisflex.core.constant.SqlConsts;
import com.mybatisflex.core.query.QueryOrderBy;
import com.mybatisflex.core.util.LambdaUtil;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 请求体基础信息
 */
@Accessors(chain = true)
@Data
public abstract class BaseReq implements Serializable {

    @ApiModelProperty(value = "pageNum")
    @Column(ignore = true)
    private int pageNum = 1;

    @ApiModelProperty(value = "pageSize")
    @Column(ignore = true)
    private int pageSize = 10;

    @ApiModelProperty(value = "排序集合")
    @Column(ignore = true)
    private List<Sort> sorts = new ArrayList<>();

    @ApiModelProperty(value = "时间区间")
    @Column(ignore = true)
    private List<DateTimeInterval> intervals = new ArrayList<>();

    public void setSorts(List<Sort> sorts) {
        sorts.forEach(f -> f.setColumn(StrUtil.toUnderlineCase(f.getColumn())));
        this.sorts = sorts;
    }

    public QueryOrderBy[] toMybatisFlexOrders() {
        return sorts.stream().map(f -> {
            if (f.getOrder().toUpperCase().contains(SqlConsts.ASC.trim().toUpperCase())) {
                return LambdaUtil.getQueryColumn(Sort::getColumn).asc();
            }
            return LambdaUtil.getQueryColumn(Sort::getColumn).desc();

        }).toArray(value -> new QueryOrderBy[sorts.size()]);
    }

    public void setIntervals(List<DateTimeInterval> intervals) {
        intervals.forEach(f -> f.setColumn(StrUtil.toUnderlineCase(f.getColumn())));
        this.intervals = intervals;
    }

    @Accessors(chain = true)
    @Data
    public static class DateTimeInterval {
        @ApiModelProperty(value = "时间字段名称")
        private String column;
        @ApiModelProperty(value = "开始时间")
        private String startDateTime;
        @ApiModelProperty(value = "结束时间")
        private String endDateTime;
    }

    @Accessors(chain = true)
    @Data
    public static class Sort {
        @ApiModelProperty(value = "排序字段名称")
        private String column;
        @ApiModelProperty(value = "顺序: ASC DESC")
        private String order;
    }
}
